<template>
  <div class="knowledge-base-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="知识库名称">
          <el-input v-model="searchForm.keyword" placeholder="请输入知识库名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="toolbar">
        <el-button type="primary" @click="showCreateDialog">创建知识库</el-button>
      </div>

      <el-table :data="tableData" v-loading="loading">
        <el-table-column prop="know_base_name" label="知识库名称" min-width="150" />
        <el-table-column prop="create_date" label="创建时间" min-width="180">
          <template #default="{ row }">
            {{ formatDate(row.create_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="create_user_id" label="创建人ID" min-width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewDetail(row)">查看详情</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handlePageChange" />
      </div>
    </el-card>

    <!-- 创建知识库弹窗 -->
    <el-dialog v-model="createDialogVisible" title="创建知识库" width="500px">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="知识库名称" required>
          <el-input v-model="createForm.knowbase_name" placeholder="请输入知识库名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreate" :loading="creating">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getKnowledgeBaseList, createKnowledgeBase, deleteKnowledgeBase } from '@/api/knowledgeBase'
import { useRouter } from 'vue-router'
const router = useRouter()


// 搜索表单
const searchForm = reactive({
  keyword: '',
  user_id: '' // 如果需要，可以从用户信息中获取
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 创建表单
const createDialogVisible = ref(false)
const createForm = reactive({
  knowbase_name: ''
})
const creating = ref(false)

// 加载数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      keyword: searchForm.keyword,
      user_id: searchForm.user_id,
      page: pagination.page,
      page_size: pagination.pageSize
    }
    const response = await getKnowledgeBaseList(params)
    console.log(response)
    const data = response.data
    tableData.value = data.list
    pagination.total = data.total_items
  } catch (error) {
    ElMessage.error('获取知识库列表失败：' + error.message)
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 日期格式化
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  pagination.page = 1
  fetchData()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchData()
}

// 页码改变
const handlePageChange = (page) => {
  pagination.page = page
  fetchData()
}

// 显示创建弹窗
const showCreateDialog = () => {
  createDialogVisible.value = true
  createForm.knowbase_name = ''
}

// 提交创建
const submitCreate = async () => {
  if (!createForm.knowbase_name.trim()) {
    ElMessage.warning('请输入知识库名称')
    return
  }

  creating.value = true
  try {
    // await createKnowledgeBase({ knowbase_name: createForm.knowbase_name })
    await createKnowledgeBase(createForm.knowbase_name)
    ElMessage.success('创建成功')
    createDialogVisible.value = false
    fetchData() // 刷新列表
  } catch (error) {
    ElMessage.error('创建失败：' + error.message)
  } finally {
    creating.value = false
  }
}

// 删除知识库
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除知识库 "${row.know_base_name}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteKnowledgeBase(row.know_base_id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败：' + error.message)
    }
  }).catch(() => { })
}

// 查看详情
const viewDetail = (row) => {
  // 跳转到文档管理视图，传递知识库ID和名称
  router.push({
    name: 'FileList',
    params: {
      knowbaseId: row.know_base_id,
      knowbaseName: row.know_base_name
    }
  })
}

// 初始化加载
onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.knowledge-base-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .toolbar {
      margin-bottom: 15px;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>